package web.servlet.user;

import com.fasterxml.jackson.databind.ObjectMapper;
import domain.User;
import domain.response.RegisterResponse;
import org.apache.commons.beanutils.BeanUtils;
import service.UserService;
import service.impl.UserServiceImpl;
import utils.LyyLogUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Map;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        Enumeration<String> headerNames = request.getHeaderNames();
        String userName = request.getParameter("userName");
        while (headerNames.hasMoreElements()){
            String hName = headerNames.nextElement();
            String header = request.getHeader(hName);
            LyyLogUtil.logD(hName+"："+header);
        }

        Map<String, String[]> parameterMap = request.getParameterMap();
        User user=new User();
        try {
            BeanUtils.populate(user,parameterMap);
        } catch (Exception e) {
            LyyLogUtil.logeE(e.getMessage());
        }
        user.setExperience(0);
        user.setRank(1);
        user.setGold(0);
        user.setGender("男");
        user.setAge(0);
        user.setCertificateType("1010");
        user.setCertificateNo(""+System.currentTimeMillis());
        LyyLogUtil.logD(user.toString());
        UserService service=new UserServiceImpl();
        User uSer = service.queryByUsername(userName);
        RegisterResponse registerResponse=new RegisterResponse();
        if(uSer!=null){
            registerResponse.setStatus(0);
            registerResponse.setErrMsg("注册失败，用户名“"+userName+"”"+"已经存在！");
        }else {
            boolean flag = service.register(user);
            if(!flag){
                registerResponse.setStatus(0);
                registerResponse.setErrMsg("注册失败，请联系管理员！");
            }
        }

        ObjectMapper mapper=new ObjectMapper();
        mapper.writeValue(response.getOutputStream(),registerResponse);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
